package com.majun.web.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 自定义日期转换器
 *
 * @author liuxun
 */
public class CustomDateConverter implements Converter<String, Date> {

    public Date convert(String source) {
        if (source != null && source.trim().length() > 0) {
            // 进行日期转换
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(source, dateTimeFormatter);
				ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.UTC);
				Date from = Date.from(zonedDateTime.toInstant());
				return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}
